﻿#region File Description

//-----------------------------------------------------------------------------
// AnimatedTexture.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------

#endregion

using Game500.Client.Src;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Game500.Client
{
  public class AnimatedTexture : Renderable
  {
    private int Frame;
    private bool Paused;

    private float TimePerFrame;
    private float TotalElapsed;
    private int framecount;
    private Texture2D myTexture;

    public AnimatedTexture(Vector3 position, float rotation)
    {
      Position = position;
      Rotation = rotation;
    }

    public bool IsPaused
    {
      get { return Paused; }
    }

    public void Load(Texture2D texture, int frameCount, int framesPerSec)
    {
      framecount = frameCount;
      myTexture = texture;
      TimePerFrame = (float)1 / framesPerSec;
      Frame = 0;
      TotalElapsed = 0;
      Paused = false;
      Origin = new Vector2(1.0f / (2 * frameCount), 0.5f);
    }

    public void UpdateFrame(float elapsed)
    {
      if (Paused)
        return;
      TotalElapsed += elapsed;
      if (TotalElapsed > TimePerFrame)
      {
        Frame++;
        if (Frame == framecount) Paused = true;
        Frame = Frame % framecount;
        TotalElapsed -= TimePerFrame;
      }
    }

    public void Reset()
    {
      Frame = 0;
      TotalElapsed = 0f;
    }

    public void Stop()
    {
      Pause();
      Reset();
    }

    public void Play()
    {
      Paused = false;
    }

    public void Pause()
    {
      Paused = true;
    }

    public override Renderable Clone()
    {
      throw new System.NotImplementedException();
    }

    public override void Render(Renderer renderer)
    {
      Render(renderer, Frame);
    }

    private void Render(Renderer renderer, int frame)
    {
      int frameWidth = myTexture.Width / framecount;
      var sourcerect = new Rectangle(frameWidth * frame, 0,
                                     frameWidth, myTexture.Height);
      renderer.RenderSprite(myTexture, Position, Origin, Vector2.One, Color.White, sourceRect: sourcerect);
    }
  }
}